package com.basker.pisces.domain.property;

import java.util.ArrayList;
import java.util.List;

import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.basker.pisces.domain.constant.DomainConstants;
import com.basker.pisces.resource.StringResources;
import com.basker.pisces.service.exception.IObjectErrorsWrapper;

/**
 * 表示非法属性值的异常
 *
 * @author hangwen
 */
public class InvalidPropertyValueException extends RuntimeException implements IObjectErrorsWrapper {

    private static final long serialVersionUID = -8802257635434616988L;
    private List<ObjectError> errors = new ArrayList<>();

    public InvalidPropertyValueException() {
        super(StringResources.get("pisces-domain.InvalidPropertyValueException.message"));
    }

    public InvalidPropertyValueException(List<ObjectError> errors) {
        this();
        Assert.notEmpty(errors, "parameter 'errors' is required");
        this.getErrors().addAll(errors);
    }

    @Override
    public List<ObjectError> getErrors() {
        return errors;
    }

    @Override
    public String getMessage() {
        String message = super.getMessage();

        if (!CollectionUtils.isEmpty(errors)) {
            message = getObjectErrorsMessage(message, errors);
        }

        return message;
    }

    @Override
    public int getStatus() {
        return DomainConstants.StatusCode.INVALID_PROPERTY_VIOLATION;
    }

    public void merge(InvalidPropertyValueException other) {
        if (other == null || CollectionUtils.isEmpty(other.errors)) {
            return;
        }

        this.errors.addAll(other.errors);
    }

    private String getObjectErrorsMessage(String message, List<ObjectError> errors) {
        String joinedMessage = ObjectError.joinErrorMessage(errors);
        return !StringUtils.isEmpty(joinedMessage) ? message + joinedMessage : message;
    }

}
